<template>
    <div class="account">
        <!-- 注册账号弹窗 -->
        <el-dialog
            title="注册账号"
            :visible.sync="registerDialog"
            width="330px"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            center
            v-dialogDrag
            @close="resetForm('registerForm'), resetForm('phone')"
            class="dialog-head"
        >
            <el-form :model="registerForm" status-icon :rules="registerRules" ref="registerForm" @submit.native.prevent>
                <el-form-item label="" prop="registerUsername">
                    <el-input type="text" placeholder="请输入手机号" v-model.trim="registerForm.registerUsername" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="" prop="registerPassword">
                    <el-input type="password" placeholder="请输入密码" v-model="registerForm.registerPassword" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="" prop="confirmPassword">
                    <el-input type="password" placeholder="请再次输入密码" v-model="registerForm.confirmPassword" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <!-- 通过图片验证码注册账号 -->
            <el-form v-if="this.number === false ? true : false" :model="phone" status-icon :rules="registerRules" ref="phone" @submit.native.prevent>
                <el-form-item prop="code1" style="height: 35px">
                    <div class="flex-hb" style="width: 270px">
                        <el-input type="text" style="width: 170px" placeholder="请输入图片验证码" v-model="phone.code1" autocomplete="off"></el-input>
                        <div style="width: 80px; margin-top: -2px">
                            <img :src="codeUrl" @click="getCode" alt="" />
                        </div>
                    </div>
                </el-form-item>
                <el-form-item prop="code">
                    <div class="flex-hbvc" style="width: 270px">
                        <el-input type="text" placeholder="请输入手机验证码" style="width: 170px" v-model.trim="phone.code" autocomplete="off"></el-input>
                        <el-button class="yzmbutton" :disabled="btnisShow" @click="getPhoneCaptchas('registerForm', 'phone')">获取验证码</el-button>
                    </div>
                    <van-count-down
                        v-show="this.number === false ? true : false"
                        class="countDown1"
                        style="color: #2a2a2a"
                        v-if="isCountDownShow"
                        :time="time"
                        format="ss s后重新发送"
                        @finish="finish"
                    ></van-count-down>
                </el-form-item>
            </el-form>

            <!-- 直接通过手机验证码注册 -->
            <el-form v-if="this.number === true ? true : false" :model="phone" status-icon :rules="registerRules" ref="phone" @submit.native.prevent>
                <el-form-item prop="code">
                    <div class="flex-hbvc" style="width: 270px">
                        <el-input type="text" placeholder="请输入手机验证码" style="width: 170px" v-model.trim="phone.code" autocomplete="off"></el-input>
                        <el-button class="yzmbutton" :disabled="btnisShow" @click="getCaptchas('registerForm')">获取验证码</el-button>
                    </div>
                </el-form-item>
                <van-count-down
                    v-show="this.number === true ? true : false"
                    class="countDown"
                    style="color: #2a2a2a"
                    v-if="isCountDownShow"
                    :time="time"
                    format="ss s后重新发送"
                    @finish="finish"
                ></van-count-down>
            </el-form>
            <el-button class="button_btn" :style="this.number === true ? 'margin-top:64px' : 'margin-top:28px'" type="primary" @click="handleRegister('registerForm', 'phone')">注册 并 登录</el-button>
        </el-dialog>
    </div>
</template>

<script>
import { captchaImage, register1, getPhoneCaptchas, getCaptchas, logins, users } from '@/api/url'
export default {
  props: {
    zhuceDialogShow: {
      type: Boolean,
      default: false
    }
  },
  created () {
    this.website_domain = box_info.m_dym_gm_static
    this.sn = box.m_sn;
  },
  mounted () {
  },
  data () {
    const validateRegisterPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.registerForm.confirmPassword !== '') {
          this.$refs.registerForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.registerPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const cellphonenumberr = (rule, value, callback) => {
      const reg = /^[1][3-9][0-9]{9}$/
      if (value === '' || value === undefined || value == null) {
        callback(new Error('请输入正确的电话号码'))
      } else {
        if ((!reg.test(value)) && value !== '') {
          callback(new Error('请输入正确的电话号码'))
        } else {
          callback()
        }
      }
    }
    return {
      sn: '',//sn码
      website_domain: '',
      text: '',
      number: '', // 值为true打开手机号码验证窗口，值为false打开图片验证窗口
      registerDialog: false, // 默认注册界面隐藏
      confirmpassword: true, //默认隐藏确认密码界面
      codeUrl: '', // 验证码图片地址
      captchaOnOff: true,
      registerForm: {
        registerUsername: '', // 注册账号
        registerPassword: '', // 注册密码
        confirmPassword: '', // 确认密码
        code: '', // 图片验证码
        uuid: ''// 获取验证码的UUID
      },
      phone: {
        code: '', // 获取的手机验证码
        code1: ''// 获取的图片验证码
      },
      uuid: '',// 获取验证码的UUID
      codes: '',//二次验证码
      phonenumber: '',//二次手机号
      isCountDownShow: false, // 默认不显示倒计时
      time: 60 * 1000, // 倒计时的时间
      btnisShow: false, // 是否禁用发送验证码按钮
      registerRules: {
        // 表单验证规则
        registerUsername: [
          { validator: cellphonenumberr, trigger: 'blur' },
          // { min: 6, max: 20, message: '账号有6~20数字、字母或下划线组成', trigger: 'blur' }
        ],
        registerPassword: [
          { validator: validateRegisterPassword, trigger: 'blur' },
          { min: 6, max: 18, message: '密码必须在6-18位之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        code: [{ required: true, message: '请输入手机验证码', trigger: 'blur' }, { pattern: /^\d{6}$/, message: '验证码长度必须是6位' }],
        code1: [{ required: true, message: '请输入图片验证码', trigger: 'blur' }, { pattern: /^\d{4}$/, message: '验证码长度必须是4位' }]
      }
    }
  },
  methods: {
    // 点击关闭时清空form表格的数据
    resetForm (registerForm) {
      this.$refs[registerForm].resetFields()
    },
    // 获取图片验证码
    getCode () {
      captchaImage().then(res => {
        // console.log(res)
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff
        if (this.captchaOnOff) {
          this.codeUrl = 'data:image/gif;base64,' + res.data.img
          this.registerForm.uuid = res.data.uuid
          this.uuid = res.data.uuid
        }
      })
    },
    // 注册账号提交
    handleRegister () {
      this.$refs.registerForm.validate(valid => {
        const channelId = box_info.m_dym_channel_id
        if (valid) {
          register1({ username: this.registerForm.registerUsername, password: this.registerForm.registerPassword, code: this.phone.code, channelId: channelId, sn: this.sn }).then(res => {
            if (res.data.code === 200) {
              setTimeout(() => {
                logins({ phoneNumber: this.registerForm.registerUsername, password: this.registerForm.registerPassword, sn: this.sn }).then(res => {
                  if (res.data.code === 200) {
                    this.$store.commit('setUser', res.data)
                    window.localStorage.setItem('token', JSON.stringify(res.data.token))
                    this.$EventBus.$emit('callTopGetInfos', 1)//调用首页的gitInfo方法
                    this.$EventBus.$emit('openProfileAuths', 1)//查询是否绑定微信和实名认证
                    this.$message({ message: '登录成功,欢迎回来', type: 'success', center: true })
                  }
                })
                setTimeout(() => {
                  this.registerDialog = false //隐藏密码注册界面
                  this.isCountDownShow = false // 隐藏倒计时
                  this.btnisShow = false// 打开禁用发送验证码按钮
                  this.registerForm.registerUsername = ''
                  this.registerForm.registerPassword = ''
                  this.phone.code = ''
                  this.phone.code1 = ''
                }, 1000)
              }, 1000)
            } else {
              this.$message({ message: res.data.msg, type: 'warning', center: true })
              this.getCode()
              this.registerDialog = false //隐藏密码注册界面
              this.isCountDownShow = false // 隐藏倒计时
              this.btnisShow = false// 打开禁用发送验证码按钮
            }
          }).catch(() => {
            if (this.captchaOnOff) {
              this.getCode()
            }
          })
        }
      })
    },
    // 直接获取手机验证码
    async getCaptchas (formName) {
      try {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const res = await getCaptchas({ phonenumber: this.registerForm.registerUsername })
            if (res.data.code === 200) {
              this.$message({ message: res.data.msg, type: 'success', center: true })
              this.isCountDownShow = true// 显示倒计时
              this.btnisShow = true// 打开禁用发送验证码按钮
            } else {
              this.$message({ message: res.data.msg, type: 'warning', center: true })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } catch (err) {
        console.log(err)
      }
    },
    //图片验证码时获取手机验证码
    async getPhoneCaptchas (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          try {
            getPhoneCaptchas({ phonenumber: this.registerForm.registerUsername, code: this.phone.code1, uuid: this.uuid }).then((res) => {
              if (res.data.code === 200) {
                this.$message({ message: res.data.msg, type: 'success', center: true })
                this.isCountDownShow = true// 显示倒计时
                this.btnisShow = true// 打开禁用发送验证码按钮
                this.phonenumber = res.data.data
              } else {
                this.$message({ message: res.data.msg, type: 'warning', center: true })
                this.getCode()
              }
            })
          } catch (err) {
            console.log(err)
          }
        } else {
          return false
        }
      })
    },
    // 获取用户信息
    async userss () {
      try {
        const res = await users()
        if (res.data.code === 200) {
          this.$store.commit('user_xx', res.data)
          // this.user_name = this.user_mes.user.userName
          // this.Grade = this.user_mes.currentmemLevel.title
          // this.Platform_currency = this.user_mes.user.balance
          this.$emit('fatherMethod', res.data);
        } else {
          console.log()
        }
        if (res.data.code === 200 && res.data.user.avatar !== '/images/profile.jpg') {
          this.img = this.website_domain + res.data.user.avatar
        } else if (res.data.user.avatar === '/images/profile.jpg') {
          this.img = require('@/assets/user/user.png')
        } else {
          console.log(res.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 倒计时结束时触发
    finish () {
      this.isCountDownShow = false// 隐藏倒计时
      this.btnisShow = false// 取消禁用发送验证码按钮
    }
  },
  computed: {},
  watch: {
    // 这里监听zhuceDialogShow对象的变化
    zhuceDialogShow: {
      deep: true,
      handler (val) {
        if (val) {
          this.registerDialog = true
        }
      }
    }
  },
  filters: {},
  components: {}
}
</script>

<style scoped lang='less'>
.dialog-head {
    /deep/.el-dialog__header {
        display: block !important;
        border-top: 1.5px solid #b4875c;
        border-left: 1.5px solid #b4875c;
        border-right: 1.5px solid #b4875c;
    }
    /deep/.el-dialog__body {
        background: url('@/assets/dialogImg/Pop-up_bj.png');
        height: 100% !important;
        border-top: 0px !important;
        border-left: 1.5px solid #b4875c;
        border-right: 1.5px solid #b4875c;
        border-bottom: 1.5px solid #b4875c;
        background-size: cover;
    }
    /deep/ .el-input__inner {
        height: 30px !important;
        line-height: 30px !important;
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid #a47e49;
        border-radius: 4px;
        color: #978152;
    }
    /deep/.el-input__inner:hover,
    .el-input__inner:focus {
        border-color: #ffb331;
    }
    /deep/ .el-input__inner:focus {
        border-color: #ffb331;
    }
    /deep/input::-webkit-input-placeholder {
        font-family: Microsoft YaHei, Microsoft YaHei-Regular;
        font-weight: 400;
        text-align: left;
        color: #978152;
        font-family: '微软雅黑';
    }
}
.yzmbutton {
    width: 80px;
    height: 30px;
    background: linear-gradient(180deg, #cdad5f, #f2ead1);
    color: #242322;
    text-align: center;
    line-height: 6px;
    padding: 0;
    border: 0px;
    border-radius: 2px !important ;
    &:hover {
        background: linear-gradient(180deg, #b19248, #d8cfb4);
        color: #242322;
    }

    &:focus {
        color: #242322;
        background: linear-gradient(180deg, #b19248, #d8cfb4);
    }
}
.countDown {
    position: absolute;
    top: 330px;
    color: #ffb331 !important;
}
.countDown1 {
    position: absolute;
    top: 50px;
    color: #ffb331 !important;
}
</style>
